#include "../include/muduo/net/TcpClient.h"
#include "../include/muduo/net/EventLoopThread.h"
#include "../include/muduo/net/TcpConnection.h" 
#include "../include/muduo/base/CountDownLatch.h"
#include <iostream>
#include <functional>



class TranslateClient
{
    public:
    TranslateClient(const std::string& sip,int sport)
    :_latch(1),
    _client(_loopthread.startLoop(),muduo::net::InetAddress(sip,sport),"TranslateClient")
    {
        _client.setConnectionCallback(std::bind(&TranslateClient::onConnect,this,std::placeholders::_1));
        _client.setMessageCallback(std::bind(&TranslateClient::onMessage,this,
        std::placeholders::_1,
        std::placeholders::_2,std::placeholders::_3));
    }

    void connect()
    {
        _client.connect();
        //阻塞等待
        _latch.wait();
    }


    bool send(const std::string& mes)
    {
        if(_conn->connected())
        {
            //连接状态正常再发送
            _conn->send(mes);
            return true;
        }
        return false;
    }
    private:
    //连接建立的回调函数，连接成功唤醒阻塞
    void onConnect(const muduo::net::TcpConnectionPtr&conn)
    {
        if(conn->connected())
        {
            _latch.countDown();//唤醒主线程中的阻塞
            _conn = conn;
        }
        else
        {
            _conn.reset();//连接关闭的操作
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr& conn,muduo::net::Buffer* buf,muduo::Timestamp)
    {

        std::cout << "翻译结果" << buf->retrieveAllAsString()<<std::endl;
    }
    private:
    muduo::CountDownLatch _latch;
    muduo::net::EventLoopThread _loopthread;
    muduo::net::TcpClient _client;
    
    muduo::net::TcpConnectionPtr _conn;
};

int main()
{
    TranslateClient cilent("127.0.0.1",8085);
    cilent.connect();
    while(1)
    {
        std::string buf;
        std::cin >> buf;
        cilent.send(buf);
    }
    return 0;

}